package org.dftproject.pgv.core.racp;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dftproject.genesis.core.http.HttpManager;

public class Session {
	
	private final String url;
	private final String username;
	private final String password;
	
	private String sessionName;
	private String sessionId;
	
	private final static Pattern tabbedLinePattern = Pattern.compile("^([^\\t]*)\\t([^\\t]*)$");
	
	public Session(String url) {
		this(url, null, null);
	}
	
	public Session(String url, String username, String password) {
		this.url = url;
		this.username = username;
		this.password = password;
	}

	public String getUrl() {
		return url;
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}
	
	public boolean connect() {
		sessionName = null;
		sessionId = null;
		
		StringBuilder sb = new StringBuilder(url);
		sb.append("client.php?action=connect&readonly=1");
		if (username != null && password != null) {
			try {
				String encodedUsername = URLEncoder.encode(username, "UTF-8");
				String encodedPassword = URLEncoder.encode(password, "UTF-8");
				sb.append("&username=").append(encodedUsername).append("&password=").append(encodedPassword);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String response = HttpManager.getDefault().getWebPage(sb.toString());
		if (response == null)
			return false;
		
		String[] lines = response.split("\n");
		if (lines.length != 2)
			return false;
		
		if ("SUCCESS".equals(lines[0]) && !lines[1].startsWith("<"))	{
			Matcher matcher = tabbedLinePattern.matcher(lines[1]);
			if (matcher.matches()) {
				sessionName = matcher.group(1);
				sessionId = matcher.group(2);
			}
		}
		
		return sessionName != null && sessionId != null;
	}
	
	public PGVGedcom[] listPGVGedcoms() {
		List<PGVGedcom> pGVGedcoms = new LinkedList<PGVGedcom>();
		
		String response = HttpManager.getDefault().getWebPage(url + "client.php?action=listgedcoms&" + getSessionComponent());
		if (response != null) {
			String[] lines = response.split("\n");
			if (lines.length > 1 && "SUCCESS".equals(lines[0]) && !lines[1].startsWith("<"))	{
				for (String line : lines) {
					Matcher matcher = tabbedLinePattern.matcher(line);
					if (matcher.matches()) {
						pGVGedcoms.add(new PGVGedcom(this, matcher.group(1), matcher.group(2)));
					}
				}
			}
		}
		
		return pGVGedcoms.toArray(new PGVGedcom[0]);
	}

	public boolean isValid() {
		return true;
	}
	
	public String getSessionName() {
		return sessionName;
	}
	
	public String getSessionId() {
		return sessionId;
	}
	
	public String getSessionComponent() {
		return sessionName + "=" + sessionId;
	}

}
